<template>
  <!--图表一-->
  <el-card class=" mt15">
    <div slot="header" class=" h4">
      公众号单粉图
    </div>
    <div class="flex flex-between">
      <div class="flex ">
        <span class="mr10">时间筛选:   </span>
        <el-date-picker
          class="mr10"
          v-model="time"
          size="mini"
          value-format="yyyy-MM-dd"
          type="daterange"
          unlink-panels
          @change="timeChange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"/>
        <el-button :type="index===1?'primary':''" @click="quickSearch(1)" size="mini">近十五天</el-button>
        <el-button :type="index===2?'primary':''" @click="quickSearch(2)" size="mini">近七天</el-button>
      </div>
      <!--<div class="flex flex-between">-->
      <!--<span class="mr10">查看值:</span>-->
      <!--<el-select-->
      <!--v-model="check_value"-->
      <!--filterable-->
      <!--placeholder="请选择"-->
      <!--size="mini">-->
      <!--<el-option-->
      <!--v-for="item in viewValue"-->
      <!--:key="item.value"-->
      <!--:label="item.label"-->
      <!--:value="item.value"-->
      <!--@change="swChange"/>-->
      <!--</el-select>-->
      <!--</div>-->
    </div>
    <bar-chart
      :datas="datas"
      :opts="opts"
      :options="originOption"
      height="500px"
    />
    <el-row type="flex">
      <el-col :span="20" :offset="0">
        <el-form label-width="80" size="small">
          <el-form-item label="公众号选择：">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全部
            </el-checkbox>
            <el-checkbox-group
              v-model="checkList"
              class="checkbox-group"
              @change="handleCheckedValueChange">
              <el-checkbox
                class="checkbox"
                v-for="item in tencentList"
                :label="item.label"
                :key="item.value"
              />
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <div class="flex">
      <span>快捷筛选：</span>
      <div>
        <el-button :type="type===1?'primary':''" @click="dataFilter(1)" size="mini">高于平均值</el-button>
        <el-button :type="type===2?'primary':''" @click="dataFilter(2)" size="mini">低于平均值</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
  import barChart from '@/views/components/chart'
  import { halfMonthAgo, sevenDaysAgo, parseTime } from '@/utils'

  export default {
    name: 'tencentChart',
    components: { barChart },
    props: {
      viewValue: {
        type: Array,
        default: () => {
          return []
        }
      },
      mp_type:{
        type: Number,
        default: 0
      }
    },
    data() {
      const startDate = new Date(new Date().getTime() - 24 * 3600 * 1000)
      const endDate = new Date()
      const startTime = parseTime(startDate, '{y}-{m}-{d}')
      const endTime = parseTime(endDate, '{y}-{m}-{d}')
      const time = [startTime, endTime]
      const colors = ['#5793f3', '#d14a61', '#675bba']

      return {
        checkList: [], //多选框已选列表
        tencentList: [],
        tencentListLength:0,
        time: time,
        check_value: '',
        type: 0,

        opts:{
          notMerge:true
        },
        performance: 0,
        originOption: {
          color: colors,
          tooltip: {
            trigger: 'axis'
          },
          grid: {
            // x: 200
          },
          label: {
            show: true,
            position: 'top'
          },
          xAxis: [{
            type: 'category',
            data: []
          }],
          yAxis: [
            {
              type: 'value',
              axisLine: {
                lineStyle: {
                  color: colors[0]
                }
              },
              // min: function(value) {
              //   return (value.min - 0.01).toFixed(2)
              // },
              name: '粉丝价值'
            }
          ],
          series: [
            {
              name: '粉丝价值',
              type: 'bar',
              yAxisIndex: 0
            }
          ]
        },
        option: {},

        isIndeterminate: false,
        checkAll: false,

        total_datas: [],
        avg_fan_income: [],
        xAxis: [],
        average: 0,
        higherList:[],
        lowerList:[],
        index: 0 ,   //1为近三十日, 2为近七日

        count:1,//是否需要取消平均值按钮
      }
    },
    computed: {
      filter_infos(val) {
        const obj = {}
        obj.begin_date = this.time && this.time[0]
        obj.end_date = this.time && this.time[1]
        obj.check_type = 3
        obj.mp_type = this.mp_type
        return obj
      },
      datas() {
        return this.option
      }
    },
    watch: {
      filter_infos(val) {
        this.getTableList()
      },
      checkList(val1, val2) {
        console.log(val1, val2)
        if (this.tencentList.length) {
          this.handleCheckedValueChange(val1)
        }
        if (this.total_datas.length) {
          const data = val1.map(item1 => {
            for (let key of this.total_datas) {
              if (key.mp_name === item1) {
                return key.avg_fan_income
              }
            }
          })

          this.setOption(data, val1)
        }
      },
    },
    mounted() {
      this.getTableList()
    },
    methods: {

      handleCheckAllChange(val) {
        this.checkList = val ? this.tencentList.map(item => item.label) : []
        this.isIndeterminate = false
      },
      handleCheckedValueChange(value) {
        let checkedCount = value.length
        this.checkAll = checkedCount === this.tencentList.length
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.tencentList.length

        if (!this.count) {
          this.type = 0
        }
        this.count--

      },
      quickSearch(index) {
        if (this.index !== index) {
          this.index = index
        } else {
          this.index = 0
        }
        this.type = 0
        if (index === 1) {
          this.time = halfMonthAgo()
        } else {
          this.time = sevenDaysAgo()
        }
      },
      swChange(val) {
        console.log(val)
      },
      timeChange() {
        this.index = 0
      },
      dataFilter(type) {
        if (this.type !== type) {
          this.type = type
          this.count = 1
        } else {
          this.type = 0
        }
        this.formatData()
      },
      formatData() {
        let datas = []
        let xAxis = []
        let option = {}
        switch (this.type) {
          case 1:
            this.total_datas.forEach(item => {
              if (item['avg_fan_income'] - this.average >= 0) {
                datas.push(item.avg_fan_income.toFixed(4))
                xAxis = this.higherList
              }
            })
            break
          case 2:
            this.total_datas.filter(item => {
              if (item['avg_fan_income'] - this.average < 0) {
                datas.push(item.avg_fan_income.toFixed(4))
                xAxis = this.lowerList
              }
            })
            break
          default:
            datas = this.avg_fan_income
            xAxis = this.xAxis
            break
        }
        this.checkList = xAxis
        this.setOption(datas, xAxis)
      },
      setOption(data, xAxis) {
        const colors = ['#5793f3', '#d14a61', '#675bba']
        const usedData = data.map(item=>{
          return (+item).toFixed(4)

        })
        const option = {
          color: colors,
          tooltip: {
            trigger: 'axis'
          },
          grid: {
            // x: 200
          },
          label: {
            show: true,
            position: 'top'
          },
          yAxis: [
            {
              type: 'value',
              axisLine: {
                lineStyle: {
                  color: colors[0]
                }
              },
              min: (value) =>{
                const min = (value.min - 0.01).toFixed(2)
                return Math.min(min,this.average)
              },
              max:(value)=>{
                return Math.max(value.max,this.average)
              },
              name: '粉丝价值'
            }
          ],
          xAxis: [{
            type: 'category',
            data: xAxis
          }],
          series: [
            {
              name: '粉丝价值',
              type: 'bar',
              data: usedData,
              yAxisIndex: 0,
              barWidth: '20%'
            }
          ]
        }
        if (this.average!=0) {
          option.series[0].markLine = {
            label: {
              show: true,
                formatter: '{b}: {c}'
            },
            precision: 4,
              data: [
              {
                name:'平均值',
                yAxis: this.average
              },
            ]
          }
        }

        this.option = option
      },
      getTableList(data) {
        const datas = {
          ...this.filter_infos
        }
        this.$get('action/TaoMpInfo/dataform', datas)
          .then(res => {
            const data = res.data.sort((a,b)=>{
              return new Date(a.date).getTime() - new Date(b.date).getTime()
            })
            const avg_fan_income = []
            const xAxis = []

            data.forEach((item, index) => {
              xAxis[index] = item.mp_name
              avg_fan_income[index] = item['avg_fan_income'].toFixed(4) || 0
            })
            this.tencentList = data.map(item => {  //原始数据的公众号列表
              return {label:item.mp_name,status:item.status}
            })
            this.checkList = data.map(item => {  //选中的公众号列表
              return item.mp_name
            })
            this.tencentListLength = this.checkList.length//原始数据的条数

            if (avg_fan_income.length) {
              const total = avg_fan_income.reduce((a, b) => {
                return Number(a) + Number(b)
              })
              this.average = (total / avg_fan_income.length).toFixed(4)
            } else {
              this.average = 0
            }

            const higherList = []
            const lowerList = []
            data.forEach(item => {
              if (item['avg_fan_income'] - this.average >= 0) {
                higherList.push(item.mp_name)
              }else{
                lowerList.push(item.mp_name)
              }
            })
            this.lowerList = lowerList
            this.higherList = higherList
            this.total_datas = data
            this.avg_fan_income = avg_fan_income
            this.xAxis = xAxis
            this.formatData()

          })
      }
    }
  }
</script>
<style scoped>
  .checkbox {
    margin-left: 15px;
  }

  .checkbox-group {
    margin-left: 80px;
  }
</style>
